class JudgmentController < ApplicationController

  before_filter :login_required
  
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @judgment_pages, @judgments = paginate :judgments, :per_page => 10, :include => "submission"
  end

  def show
    @judgment = Judgment.find(params[:id])
  end

  def new
    @judgment = Judgment.new
  end

  def create
    @judgment = Judgment.new(params[:judgment])
    if @judgment.save
      flash[:notice] = 'Judgment was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit          
    
    @judgment = Judgment.find(params[:id], :include => "submission")  
    
    if @judgment.submission.data  
      @submission_data = HashModel::Model.new(YAML::load(@judgment.submission.data))
    else    
      @submission_data = HashModel::Model.new({})
    end 
    
    if @judgment.data  
      @judgment_data = HashModel::Model.new(@judgment.data)
    else    
      @judgment_data = HashModel::Model.new({})
    end
  end
                                                        

  def update
    @judgment = Judgment.find(params[:id])  
    judgment_attributes = params[:judgment]
    judgment_attributes[:score] = calculate_final_score(params[:judgment_data])
    judgment_attributes[:data] = params[:judgment_data]
    if @judgment.update_attributes(judgment_attributes)
      flash[:notice] = 'Judgment was successfully updated.'
      redirect_to :controller => 'workitem', :action => 'list'
    else              
      if @judgment.submission.data  
        logger.debug "TEST"
        @submission_data = HashModel::Model.new(YAML::load(@judgment.submission.data))
      else    
        @submission_data = HashModel::Model.new({})
      end
      
      render :action => 'edit'
    end
  end

  def complete
    @judgment = Judgment.find(params[:id])
    @judgment.complete = true
    @judgment.save!
    redirect_to :controller => 'workitem', :action => 'list'
  end

  def destroy  
    if current_user.is_admin?
      Judgment.find(params[:id]).destroy
    end
    redirect_to :action => 'list'
  end

  def final_score
    render :text => sprintf("%d", calculate_final_score(params[:judgment_data]))
  end 
  
  def calculate_final_score(p)
    final_score = 0
    p.each { |k,v|
      next if not v
      next if /\A\Z/.match(v.to_s)
      next if not /\Ascore/.match(k.to_s)

      if (m = /\A([+\-]?[\d\.]+)\Z/.match(v.to_s))   
        logger.debug "adding #{m[1]} to #{final_score} (float: #{m[1].to_f})"
        final_score = final_score + m[1].to_f
      else
        logger.error "v is not a number #{v}"
        final_score = -1
        break;
      end
    }
    final_score
  end 
end
